# coding=utf-8
import copy
import os
import re
import sys
import traceback

import openpyxl
import pandas
import pandas as pd
from loguru import logger
from openpyxl.reader.excel import load_workbook
from openpyxl.styles import Font, Color

from models.stock_model import StockNumber, DayInfo
from mylib import download_all
from mylib.mycsv import sort_csv2
from send_email import send_email_xlsx
from update_sh import get_sh_pct_dict_down_date


def get_3down_len(cal_len, today_date, sn, N=9):
    """
    获取最近N次下跌，连续下跌天数计数
    """
    sc = f'stocks/{sn.ts_code}.csv'
    if not os.path.exists(sc):
        return None, None, None
    while not os.path.exists(sc):
        download_all.analysis_stock(sn)
    df = pandas.read_csv(sc)
    while str(df.iloc[0]['trade_date']) < str(today_date):
        download_all.analysis_stock(sn)
        df = pandas.read_csv(sc)
        if str(df.iloc[0]['trade_date']) >= str(today_date):
            logger.info(str(df.iloc[-1]['trade_date']).replace('-', ''))
            break
        else:
            logger.error(sn.name)
            return None, None, None
    today_d = None
    result_arr = []
    temp_arr = []
    for row in df.index:
        if cal_len == 0:
            break
        d = DayInfo(sn, df.loc[row])
        if d.trade_date_str > today_date:
            continue
        if today_d is None:
            today_d = copy.deepcopy(d)
            if today_d.trade_date_str != today_date:
                return None, None, None
        # temp_arr = [DayInfo(sn, df.loc[row + i]) for i in range(9)]
        temp_arr.append(d)
        if len(temp_arr) == 2 and temp_arr[0].low > temp_arr[1].low:
            return None, None, None
        if len(temp_arr) == N:
            pct5 = round((temp_arr[0].low - temp_arr[-1].high) / temp_arr[-1].low * 100, 2)
            result_arr.append(pct5)
            temp_arr.pop(0)
            cal_len -= 1
    res = re.findall('stocks/(.*).csv', sc)
    link_code_arr = res[0].split('.')
    link_code = f'{link_code_arr[1]}{link_code_arr[0]}'
    hyperlink = f'"https://xueqiu.com/S/{link_code}"'
    date_arr_hyp = f'=HYPERLINK({hyperlink})'
    logger.info(f'{today_date}, {sn.name}, {hyperlink}')
    result_arr2 = [str(i) for i in result_arr]
    return today_d, result_arr2, date_arr_hyp


def get_all_stock_csv_path():
    for root, dirs, files in os.walk('stocks'):
        return [os.path.join(root, item) for item in files]


def run_down(stocks, cal_date, cal_len, sh_pct_dict, N):
    today_date = cal_date[0]
    dname = os.path.basename(__file__).split('.')[0]
    log_dir = f'result_{dname}'
    if not os.path.exists(log_dir):
        os.makedirs(log_dir)
    full_path_csv = f'{log_dir}/{today_date}_aaud.csv'
    f_tk = open(full_path_csv, 'w', encoding='utf-8')

    sh_date_color = ['FFFFFF']
    sh_date_color_font = ['000000']
    for d in cal_date[::-1]:
        if float(sh_pct_dict.get(d)) <= 0:
            sh_date_color.append('FF00FF')
            sh_date_color_font.append('FFFFFF')
        else:
            sh_date_color.append('FFFFFF')
            sh_date_color_font.append('000000')
    sh_date_color.append('FFFFFF')
    sh_date_color.append('FFFFFF')
    sh_date_color.append('FFFFFF')
    sh_date_color.append('FFFFFF')
    sh_date_color.append('FFFFFF')
    sh_date_color_font.append('000000')
    sh_date_color_font.append('000000')
    sh_date_color_font.append('000000')
    sh_date_color_font.append('000000')
    sh_date_color_font.append('000000')

    cal_date_str = ','.join(cal_date[::-1])
    f_tk.write(f'日期,{cal_date_str},连接,行业,名称,代码,当前价格')
    df = pd.read_csv('cal_ops/all.csv')
    full_path_txt = f'{log_dir}/{today_date}_get_aaud.txt'
    if os.path.exists(full_path_txt):
        os.remove(full_path_txt)
    logger.add(full_path_txt, format='{message}')
    for row in df.index:
        sn = StockNumber(df.loc[row])
        if 'ST' in sn.name:
            continue
        if '退' in sn.name:
            continue
        if not str(sn.ts_code).startswith('60') \
                and not str(sn.ts_code).startswith('30') \
                and not str(sn.ts_code).startswith('00'):
            continue
        if stocks and sn.name not in stocks:
            continue
        logger.info(f'{row} {sn}')
        # if sn.name not in [
        #     '豪美新材',
        # ]:
        #     continue
        try:
            """
                elf.name = sn.name
                self.ts_code = sn.ts_code
                self.industry = sn.industry
                self.trade_date = df_row_data['trade_date']
                self.open = df_row_data['open']
                self.high = df_row_data['high']
                self.low = df_row_data['low']
                self.close = float(df_row_data['close'])
                self.pre_close = df_row_data['pre_close']
                self.change = df_row_data['change']
                self.pct_chg = float(df_row_data['pct_chg'])
                self.vol = df_row_data['vol']
                self.amount = df_row_data['amount']
            """
            today_d, result_arr2, date_arr_hyp = get_3down_len(cal_len, today_date, sn, N)
            if today_d is None:
                continue
            if len(result_arr2) < cal_len:
                continue
            result_arr_str = ','.join(result_arr2[::-1])
            w_msg = f'\n{today_date},{result_arr_str},{date_arr_hyp},{sn.industry},{sn.name},{sn.ts_code},{today_d.close}'
            logger.info(f'{today_date}, {sn.name}, {w_msg}')
            f_tk.write(w_msg)
            f_tk.flush()
        except Exception as e:
            print(e, traceback.format_exc())

    if os.path.exists(full_path_txt):
        os.remove(full_path_txt)

    f_tk.close()
    # True 从小到大， False 从大到小
    # 当前下跌次数最多，成交量翻倍最少，距离最大
    # save_path_csv = full_path_csv.replace('.csv', f'_{cnt_number}.csv')
    if os.path.exists(full_path_csv):
        save_path_csv = full_path_csv.replace('.csv', f'_sort.csv')
        # sort_csv2(save_path_csv, full_path_csv, [cal_date[1], cal_date[0], '行业'], [True, True, True])
        # sort_csv2(save_path_csv, full_path_csv, ['行业', today_date], [True, True])
        # sort_csv2(save_path_csv, full_path_csv, [today_date], [True])
        sort_csv2(save_path_csv, full_path_csv, [cal_date[0]], [True])
        result_xlsx = csv2excel(save_path_csv)
        os.remove(save_path_csv)
        color_excel_file_path = red_min_value(result_xlsx, cal_len, sh_date_color, sh_date_color_font)
        os.remove(result_xlsx)
        send_email_xlsx.send_xlsx(f'{today_date}_aan_最近{N}日累计下跌排名', color_excel_file_path)

        # sort_csv2(save_path_csv, full_path_csv, ['行业', today_date], [True, True])
        # result_xlsx = csv2excel(save_path_csv)
        # os.remove(save_path_csv)
        # color_excel_file_path = red_min_value(result_xlsx, cal_len)
        # os.remove(result_xlsx)
        # send_email_xlsx.send_xlsx(f'{today_date}_aaud_行业', color_excel_file_path)


def red_min_value(excel_path, cal_len, sh_date_color, sh_date_color_font):
    wb = load_workbook(excel_path)
    sheet = wb['Sheet1']
    # 标记最小值的背景色为红色
    pre_cell = None
    for row in sheet[2:sheet.max_row]:
        color_idx = 0
        for cell in row:
            if 1 < cell.col_idx <= (1 + cal_len):
                if float(cell.value) <= float(pre_cell.value):
                    # cell.fill = openpyxl.styles.PatternFill(start_color='00FF00', end_color='00FF00', fill_type='solid')
                    cell.fill = openpyxl.styles.PatternFill(start_color='009900', end_color='009900', fill_type='solid')
                    # font = Font(color=Color(rgb='FFFFFF'))  # 白色
                    # cell.font = font
                else:
                    # cell.fill = openpyxl.styles.PatternFill(start_color='FF0000', end_color='FF0000', fill_type='solid')
                    # cell.fill = openpyxl.styles.PatternFill(start_color='FFFFFF', end_color='FFFFFF', fill_type='solid')
                    color_sh_down = sh_date_color[color_idx]
                    cell.fill = openpyxl.styles.PatternFill(start_color=color_sh_down, end_color=color_sh_down,
                                                            fill_type='solid')
            pre_cell = cell

            # 设置上证涨跌颜色
            font = Font(color=Color(rgb=sh_date_color_font[color_idx]))
            cell.font = font
            color_idx += 1

    # 保存工作簿
    color_excel_file_path = excel_path.replace('.xlsx', '_color.xlsx')  # 加载Excel文件
    if os.path.exists(color_excel_file_path):
        os.remove(color_excel_file_path)
    sheet.freeze_panes = "C2"
    wb.save(color_excel_file_path)
    return color_excel_file_path


def csv2excel(full_path_csv):
    # csv转excel
    try:
        excel_path = str(full_path_csv).replace('.csv', '.xlsx')
        # 读取CSV文件
        df = pd.read_csv(full_path_csv)
        df.to_excel(excel_path, index=False)
        return excel_path
    except Exception as e:
        print(e)


if __name__ == '__main__':
    # 计算离最近左右N日，计算当前价与顶点下跌幅度
    start_index = 0
    cal_len = 10
    N = 60
    try:
        arguments = sys.argv[1:]
        if arguments:
            start_index = int(arguments[0])
            cal_len = int(arguments[1]) if len(arguments) >= 2 else cal_len
            N = int(arguments[2]) if len(arguments) >= 3 else N
    except Exception as e:
        start_index = 0
        cal_len = 10
        N = 60
        logger.error(e)

    # cal_date = [
    #     '20240520',
    # ]
    # start_index = 367
    sh_date, sh_pct_dict = get_sh_pct_dict_down_date()
    cal_date = sh_date[start_index:start_index + cal_len]
    stocks = [
        # '菜百股份',
        # '通威股份',
        # '中天科技',
        # '均胜电子',
        # '长江电力',
        # '隆基绿能',
        # '华电科工',
        # '明阳智能',
        # '众鑫股份',
    ]
    # for N in range(5, 10):
    run_down(stocks, cal_date, cal_len, sh_pct_dict, N)
